package com.controller;

import com.service.HelperService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.CacheControl;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * @author qindengfeng
 * @date 2019/11/8 16:19
 */
@RestController
public class DocHelperController {

    @Autowired
   private HelperService helperService;

    @RequestMapping("test")
    public  ResponseEntity<String> test(String version){
        if(version==null){
            version="1";
        }
        return ResponseEntity.ok().cacheControl(CacheControl.maxAge(1, TimeUnit.HOURS)).eTag(version).body("test");

    }

    @RequestMapping("init")
    public void init(HttpServletResponse response) throws IOException, TemplateException {
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        configuration.setDirectoryForTemplateLoading(new File( DocHelperController.class.getResource("/templates/").getPath()));
        Template template = configuration.getTemplate("database.ftl");
        List<Map<String, Object>> allTableInfo = helperService.getAllTableInfo();
        for(Map<String, Object> item:allTableInfo ){
            String tableName = (String) item.get("TABLENAME");
            List<Map<String, Object>> tableFileInfo = helperService.getTableFileInfo(tableName);
            tableFileInfo.get(0).put("isKey","Y");
            item.put("fileInfo",tableFileInfo);
        }
        Map<String,Object> objectMap=new HashMap<>(1);
        objectMap.put("data",allTableInfo);
        response.setHeader("Content-Disposition", "attachment;fileName=" + "xxxx.doc");
        Writer out = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), "utf-8"),10240);
        template.process(objectMap, out);
        out.close();
    }
}
